package cn.xd.base.application.service.query.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.xd.base.application.assembler.DictAssembler;
import cn.xd.base.application.assembler.DictGroupAssembler;
import cn.xd.base.application.dto.query.DictQuery;
import cn.xd.base.application.service.query.DictQueryAppService;
import cn.xd.base.domain.bean.response.DictDTO;
import cn.xd.base.domain.bean.response.DictGroupDTO;
import cn.xd.base.persistence.dos.DictDO;
import cn.xd.base.persistence.dos.DictGroupDO;
import cn.xd.base.persistence.mps.DictGroupMpService;
import cn.xd.base.persistence.mps.DictMpService;
import cn.xd.common.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DictQueryAppServiceImpl implements DictQueryAppService {

    @Resource
    private DictMpService dictMpService;

    @Resource
    private DictGroupMpService dictGroupMpService;

    /**
     * 获取字典分页
     *
     * @param dictQuery
     * @return 字典分页
     */
    @Override
    public Page<DictDTO> getDictPage(DictQuery dictQuery) {
        LambdaQueryWrapper<DictDO> wrapper = new LambdaQueryWrapper<>();
        // 名称
        wrapper.like(StrUtil.isNotBlank(dictQuery.getName()), DictDO::getName, dictQuery.getName());
        // 编码
        wrapper.eq(StrUtil.isNotBlank(dictQuery.getCode()), DictDO::getCode, dictQuery.getCode());
        wrapper.eq(ObjUtil.isNotNull(dictQuery.getGroupId()), DictDO::getGroupId, dictQuery.getGroupId());
        wrapper.eq(ObjUtil.isNotNull(dictQuery.getAutoDictKey()), DictDO::getAutoDictKey, dictQuery.getAutoDictKey());
        wrapper.eq(StrUtil.isNotBlank(dictQuery.getDictKeyType()), DictDO::getDictKeyType, dictQuery.getDictKeyType());
        return dictMpService.getPage(wrapper.orderByDesc(DictDO::getId), DictAssembler.INSTANCE, dictQuery);
    }

    @Override
    public DictDTO getDictByCode(String code) {
        if (StrUtil.isBlank(code)) {
            throw new BizException("字典编码不存在");
        }
        LambdaQueryWrapper<DictDO> wrapper = new LambdaQueryWrapper<>();
        // 编码
        wrapper.eq(DictDO::getCode, code);
        return DictAssembler.INSTANCE.fromData(dictMpService.getOneForLimitOneResult(
                Wrappers.lambdaQuery(DictDO.class).eq(StrUtil.isNotBlank(code), DictDO::getCode, code)).isEmptyThrow("未找到字典"));
    }

    /**
     * 获取字典分页
     *
     * @return 字典分页
     */
    @Override
    public List<DictGroupDTO> getDictGroup() {
        return (List<DictGroupDTO>) dictGroupMpService.getList(Wrappers.lambdaQuery(DictGroupDO.class).orderByDesc(DictGroupDO::getId), DictGroupAssembler.INSTANCE).get();
    }
}
